package com.hxgis.oc.product.file;

import com.hxgis.oc.config.OConfig;
import com.hxgis.oc.product.w3d.W3dConvTask;
import com.hxgis.oc.product.base.ProduceTask;
import com.hxgis.oc.product.base.ProductFactory;
import com.hxgis.oc.product.base.ProductFactoryWorker;
import com.hxgis.oc.util.ds.FileDatabase;
import com.hxgis.oc.util.ds.FileDatabaseManager;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

@Slf4j
@Component
public class FileProductManager extends ProductFactory {
    @Getter
    private static final String factoryName = "file";
    private ProductFactoryWorker worker;

    public FileProductManager() {
        super(factoryName, OConfig.getConfig().getProductFile(), 1);
    }

    public ProductFactoryWorker getWorker() {
        if (worker == null) {
            worker = new ProductFactoryWorker();
        }
        return worker;
    }

    @Override
    protected void onPublish(ProduceTask o) {
        String ds = o.getDataSet();
        if (!accept(ds)) {
            return;
        }
        if (DownloadTask.class == o.getClass()) {
            submit(o);
        }
    }

    @Override
    protected void onRetrieve(ProduceTask o) {
        String ds = o.getDataSet();
        if (!accept(ds)) {
            return;
        }

        if (W3dConvTask.class == o.getClass()) {
            W3dConvTask task = (W3dConvTask) o;
            FileDatabase fileDatabase = getFileDatabase(ds);
            if (fileDatabase != null) {
                File file = task.getInputFile();
                fileDatabase.delete(ds, task.getFileID(), file.getName());
            }
        }
    }
}
